<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="设备编号" prop="mac">
        <el-input v-model="queryParams.mac" placeholder="请输入设备编号" clearable style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 300px"
          @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="学工号" prop="idCardNumber">
        <el-input v-model="queryParams.idCardNumber" placeholder="请输入学工号" clearable style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="校区" prop="cellId">
        <el-select v-model="queryParams.cellId" placeholder="请选择校区" clearable style="width: 200px"
          @change="handleQueryCellChange">
          <el-option v-for="item in cellOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="unitId">
        <el-select v-model="queryParams.unitId" placeholder="请选择楼栋" clearable style="width: 200px"
          :disabled="!queryParams.cellId" @change="handleQueryUnitChange">
          <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floorId">
        <el-select v-model="queryParams.floorId" placeholder="请选择楼层" clearable style="width: 200px"
          :disabled="!queryParams.unitId" @change="handleQueryFloorChange">
          <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id">
            {{ item.name }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房间" prop="homeId">
        <el-select v-model="queryParams.homeId" placeholder="请选择房间" clearable style="width: 200px"
          :disabled="!queryParams.floorId">
          <el-option v-for="item in roomOptions" :key="item.id" :label="item.roomName" :value="item.id">
            {{ item.roomName }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lock:openlock:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lock:openlock:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lock:openlock:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lock:openlock:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="openlockList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="设备编号" align="center" prop="mac" /> -->
      <el-table-column label="地址" align="center">
        <template #default="scope">
          {{ scope.row.cellName }} {{ scope.row.unitName }} {{ scope.row.floorName }} {{ scope.row.roomName }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" prop="action" /> -->
      <el-table-column label="学工号" align="center" prop="idCardNumber" />
      <el-table-column label="名字" align="center" prop="username" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.relation" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="开门时间" align="center" prop="createTime" width="180" />
      <el-table-column label="开门方式" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.key_type" :value="scope.row.type" />
        </template>
      </el-table-column>
	  <el-table-column label="备注" align="center" prop="remark" width="180" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
      <!--    <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lock:openlock:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lock:openlock:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改开门记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="日志id" prop="logId">
          <el-input v-model="form.logId" placeholder="请输入日志id" />
        </el-form-item>
        <el-form-item label="日志记录时间" prop="createTime">
          <el-input v-model="form.createTime" placeholder="请输入日志记录时间" />
        </el-form-item>
        <el-form-item label="操作" prop="action">
          <el-input v-model="form.action" placeholder="请输入操作" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="学工号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入学工号" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-cascader v-model="locationIds" :options="locationOptions" :props="locationProps"
            @change="handleLocationChange" placeholder="请选择位置" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="名字" prop="username">
          <el-input v-model="form.username" placeholder="请输入名字" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listOpenlock,
    getOpenlock,
    delOpenlock,
    addOpenlock,
    updateOpenlock
  } from "@/api/lock/openlock";
  import {
    listCell2
  } from "@/api/lock/cell";
  import {
    listUnit2
  } from "@/api/lock/unit";
  import {
    listFloor2
  } from "@/api/lock/floor";
  import {
    listHome2
  } from "@/api/lock/home";

  export default {
    name: "Openlock",
    dicts: ['relation','key_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 开门记录表格数据
        openlockList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 校区选项
        cellOptions: [],
        // 楼栋选项
        unitOptions: [],
        // 楼层选项
        floorOptions: [],
        // 房间选项
        roomOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          mac: null,
          createTime: null,
          action: null,
          phone: null,
          type: null,
          cellId: null,
          unitId: null,
          floorId: null,
          roomId: null,
          username: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        // 位置级联选择器的值
        locationIds: [],
        // 位置级联选择器的配置
        locationProps: {
          checkStrictly: false,
          value: 'id',
          label: 'name',
          lazy: true,
          lazyLoad: this.locationLazyLoad
        },
        // 位置级联选择器的选项
        locationOptions: [],
      };
    },
    created() {
      this.getList();
      this.getCellList();
    },
    methods: {
      /** 查询开门记录列表 */
      getList() {
        this.loading = true;
        const params = { ...this.queryParams };

        // 设置日期范围参数
        if (this.dateRange && this.dateRange.length === 2) {
          params.beginTime = this.dateRange[0];
          params.endTime = this.dateRange[1];
        }

        // 查询开门记录
        listOpenlock(params).then(response => {
          this.openlockList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 获取校区列表 */
      getCellList() {
        listCell2().then(response => {
          this.cellOptions = response.rows;
        });
      },
      /** 获取楼栋列表 */
      getUnitList(cellId) {
        this.unitOptions = [];
        this.queryParams.unitId = undefined;
        this.form.unitId = undefined;
        this.floorOptions = [];
        this.queryParams.floorId = undefined;
        this.form.floorId = undefined;
        this.roomOptions = [];
        this.queryParams.roomId = undefined;
        this.form.roomId = undefined;

        if (!cellId) return;

        listUnit2({
          cellId: cellId
        }).then(response => {
          this.unitOptions = response.rows;
        });
      },
      /** 获取楼层列表 */
      getFloorList(unitId) {
        this.floorOptions = [];
        this.queryParams.floorId = undefined;
        this.form.floorId = undefined;
        this.roomOptions = [];
        this.queryParams.roomId = undefined;
        this.form.roomId = undefined;

        if (!unitId) return;

        console.log('正在加载楼层列表，楼栋ID:', unitId);

        listFloor2({
          unitId: unitId
        }).then(response => {
          console.log('楼层数据响应:', response);
          // 将楼层数字转换为名称
          this.floorOptions = response.rows.map(floor => ({
            ...floor,
            name: this.getFloorName(floor.floorName || floor.name)
          }));
          console.log('设置后的floorOptions:', this.floorOptions);
        }).catch(error => {
          console.error('加载楼层列表失败:', error);
        });
      },
      /** 将楼层数字转换为名称 */
      getFloorName(floor) {
        const floorNum = parseInt(floor);
        if (isNaN(floorNum)) return floor;

        if (floorNum < 0) {
          return `地下${Math.abs(floorNum)}层`;
        } else {
          return `${floorNum}层`;
        }
      },
      /** 获取房间列表 */
      getRoomList(floorId) {
        this.roomOptions = [];
        this.queryParams.roomId = undefined;
        this.form.roomId = undefined;

        if (!floorId) return;

        console.log('正在加载房间列表，楼层ID:', floorId);
        
        listHome2({
          floorId: floorId
        }).then(response => {
          this.roomOptions = response.rows || [];
          console.log('设置后的roomOptions:', this.roomOptions);
        }).catch(error => {
          console.error('加载房间列表失败:', error);
        });
      },
      /** 搜索条件校区选择改变时触发 */
      handleQueryCellChange(value) {
        this.getUnitList(value);
      },
      /** 搜索条件楼栋选择改变时触发 */
      handleQueryUnitChange(value) {
        this.getFloorList(value);
      },
      /** 搜索条件楼层选择改变时触发 */
      handleQueryFloorChange(value) {
        console.log('楼层选择变化，值:', value, '类型:', typeof value);
        const selectedFloor = this.floorOptions.find(f => f.id == value); // 使用 == 而不是 === 来处理类型转换
        if (selectedFloor) {
          this.queryParams.floorName = selectedFloor.name;
        }
        this.getRoomList(value);
      },
      /** 表单校区选择改变时触发 */
      handleCellChange(value) {
        this.getUnitList(value);
      },
      /** 表单楼栋选择改变时触发 */
      handleUnitChange(value) {
        this.getFloorList(value);
      },
      /** 表单楼层选择改变时触发 */
      handleFloorChange(value) {
        const selectedFloor = this.floorOptions.find(f => f.id === value);
        if (selectedFloor) {
          this.form.floorName = selectedFloor.name;
        }
        this.getRoomList(value);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          mac: null,
          logId: null,
          createTime: null,
          trackId: null,
          action: null,
          keyId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          phone: null,
          type: null,
          cellId: null,
          unitId: null,
          floorId: null,
          roomId: null,
          username: null
        };
        this.locationIds = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加开门记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getOpenlock(id).then(response => {
          this.form = response.data;
          // 设置级联选择器的值
          if (this.form.cellId && this.form.unitId && this.form.floorId && this.form.roomId) {
            this.locationIds = [this.form.cellId, this.form.unitId, this.form.floorId, this.form.roomId];
          }
          this.open = true;
          this.title = "修改开门记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateOpenlock(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addOpenlock(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除开门记录编号为"' + ids + '"的数据项？').then(function() {
          return delOpenlock(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('lock/openlock/export', {
          ...this.queryParams
        }, `openlock_${new Date().getTime()}.xlsx`)
      },
      /** 位置级联选择器懒加载 */
      locationLazyLoad(node, resolve) {
        const {
          level,
          value
        } = node;

        // 加载校区
        if (level === 0) {
          listCell2().then(response => {
            const nodes = response.rows.map(item => ({
              ...item,
              leaf: false
            }));
            resolve(nodes);
          });
          return;
        }

        // 加载楼栋
        if (level === 1) {
          listUnit2({
            cellId: value
          }).then(response => {
            const nodes = response.rows.map(item => ({
              ...item,
              leaf: false
            }));
            resolve(nodes);
          });
          return;
        }

        // 加载楼层
        if (level === 2) {
          listFloor2({
            unitId: value
          }).then(response => {
            const nodes = response.rows.map(item => ({
              ...item,
              name: this.getFloorName(item.floorName || item.name),
              leaf: false
            }));
            resolve(nodes);
          });
          return;
        }

        // 加载房间
        if (level === 3) {
          listHome2({
            floorId: value
          }).then(response => {
            const nodes = response.rows.map(item => ({
              ...item,
              name: item.roomName, // 确保使用roomName作为显示名称
              leaf: true
            }));
            resolve(nodes);
          });
        }
      },
      /** 位置选择改变时触发 */
      handleLocationChange(value) {
        if (value && value.length === 4) {
          this.form.cellId = value[0];
          this.form.unitId = value[1];
          this.form.floorId = value[2];
          this.form.roomId = value[3];
        } else {
          this.form.cellId = null;
          this.form.unitId = null;
          this.form.floorId = null;
          this.form.roomId = null;
        }
      },
      /** 日期范围变化事件 */
      handleDateRangeChange(value) {
        this.dateRange = value;
      },
    }
  };
</script>
